#! /usr/bin/env python
# -*- mode: python -*-
###
#
# (c) 2000-2007 Wijnand Modderman <wijnand at tehmaze dot com>
# All rights reserved. See docs/LICENSE
#
###

__revision__ = '$Hg:$'

# system imports
import os
import shutil
import sys

# DDB imports
userRegister = None
makeMask     = None

def yesno(q, default='y', answers={'y': True, 'n': False}):
    answer  = 'XXX'
    choices = []
    options = answers.keys()
    options.sort()
    for x in options:
        if x==default:
            choices.append(x.upper())
        else:
            choices.append(x.lower())
    while not answer.lower() in [x.lower() for x in answers.keys()+['']]:
        sys.stdout.write('%s [%s]: ' % (q, '/'.join(choices)))
        sys.stdout.flush()
        answer = sys.stdin.readline().strip()
    if not answer:
        answer=default
    return answers[answer]

def configure_userFile():
    if not os.path.isfile('config/users.ini'):
        if os.path.isfile('config/users.ini.dist'):
            if yesno('copy config/users.ini.dist to config/users.ini'):
                shutil.copyfile('config/users.ini.dist', 'config/users.ini')
            else:
                print 'user configuration aborted'
                sys.exit(1)

def gen_prompt(level=[], prompt='>'):
    sys.stdout.write('%s%s ' % (' '.join(level), prompt))
    sys.stdout.flush()
    return sys.stdin.readline().strip()

def gen_menu(menu, title='MENU', level=[]):
    keys = menu.keys()
    keys.sort()
    print title
    for key in keys:
        print '    %-4s %s' % (key, menu[key])
    choice = -1
    while not choice in keys:
        input = gen_prompt(level)
        try:
            choice = int(input)
        except ValueError:
            print 'input invalid'
    return choice

def userShell_editUser(username):
    if not userRegister.userCheck(username):
        print 'user "%s" not found' % username
        return
    masks   = userRegister.config.get(username, 'mask')
    if not masks:
        masks = []
    schoise = -1
    while schoise not in [0,8]:
        print 'current masks:', masks
        schoise = gen_menu({
            1:  'add mask',
            2:  'remove mask',
            8:  'return to main menu',
            9:  'return to main menu and discard changes'
        }, 'Add user "%s"' % username, ['add-user', username])
        if schoise == 1:
            masks.append(makeMask(gen_prompt(['add-user', username, '(enter new mask)'], ':')))
            print 'added new mask:', masks[-1]
        elif schoise == 2:
            match = gen_prompt(['add-user', username, '(enter pattern)'], ':')
            oldmasks = masks
            masks = [x for x in oldmasks if not match in x]
    if schoise == 8:
        print 'changes saved in memory'
        userRegister.config.set(username, 'mask', masks)
    else:
        print 'changes not saved in memory'

def configure_userShell():
    # main menu
    choise = -1
    while choise not in [8, 9]:
        names = userRegister.names()
        names.sort()
        print 'users in system:', names
        choise = gen_menu({
            1:  'add user',
            2:  'edit user',
            3:  'remove user',
            8:  'save and quit',
            9:  'quit without saving'
        }, 'Main menu')
        if choise == 1:
            username = gen_prompt(['add-user',  '(enter new username)'], ':')
            if not userRegister.userCheck(username):
                userRegister.add(username, '')
                userShell_editUser(username)
            else:
                print 'user "%s" already exists' % username
        elif choise == 2:
            username = gen_prompt(['edit-user', '(enter username)'], ':')
            userShell_editUser(username)
        elif choise == 3:
            username = gen_prompt(['remove-user', '(enter username)'], ':')
            if userRegister.userCheck(username):
                userRegister.remove(username)
            else:
                print 'user "%s" does not exist' % username
    if choise == 8:
        userRegister.config.save()
        print 'changes saved to userfile ...'
    else:
        print 'changes not to userfile ...'

if __name__ == '__main__':
    configure_userFile()
    from ddb.log import init, log
    init()
    from ddb.user import userRegister, makeMask
    configure_userShell()

# vim:ts=4:sw=4:et:
